package com.basic.cli;

import com.basic.cli.command.ConfigCommand;
import com.basic.cli.command.GenerateCommand;
import com.basic.cli.command.ListCommand;
import picocli.CommandLine;
import picocli.CommandLine.Command;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 命令执行器
 */
@Command(name = "basic", mixinStandardHelpOptions = true)
public class CommandExecutor implements Runnable {

    private final CommandLine commandLine;

    {
        commandLine = new CommandLine(this)
                .addSubcommand(new GenerateCommand())
                .addSubcommand(new ConfigCommand())
                .addSubcommand(new ListCommand());
    }

    @Override
    public void run() {
        // 不输入子命令时，给出友好提示
        System.out.println("请输入具体命令，或者输入 --help 查看命令提示");
    }

    /**
     * 执行命令
     *
     * @param args
     * @return
     */
    public Integer doExecute(String[] args) {

        if(args[0].equals("generate")){
            Class<GenerateCommand> clazz = GenerateCommand.class;
            Field[] fields = clazz.getDeclaredFields();
            List<String> list=new ArrayList<>();

            for (Field field : fields) {
                if (field.isAnnotationPresent(CommandLine.Option.class)) {
                    CommandLine.Option option = field.getAnnotation(CommandLine.Option.class);
                    String[] names = option.names();
                    list.add(names[0]);
                }
            }
            args=new String[list.size()+1];
            args[0]="generate";
            for(int i=0;i<list.size();i++){
                args[i+1]=list.get(i);
            }
        }
        return commandLine.execute(args);
    }
}
